package com.xxl.job.executor.service.thread;

import com.ruoyi.bizsys.domain.RepaymentOrder;
import com.ruoyi.bizsys.service.IRepaymentOrderService;
import com.ruoyi.business.service.IBRepaymentService;
import com.ruoyi.common.core.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.Callable;

@Slf4j
public class TransferToUsThread implements Callable {
    private String threadName;
    private String redisName;
    private RedisCache redisCache;

    private IBRepaymentService iBRepaymentService;
    private IRepaymentOrderService iRepaymentOrderService;

    public TransferToUsThread(String threadName, String redisName,
                              IBRepaymentService iBRepaymentService, RedisCache redisCache, IRepaymentOrderService iRepaymentOrderService) {
        super();
        this.threadName = threadName;
        this.redisName = redisName;
        this.redisCache = redisCache;
        this.iBRepaymentService = iBRepaymentService;
        this.iRepaymentOrderService = iRepaymentOrderService;
    }

    @Override
    public String toString() {
        return "BatchJobThread [threadName=" + threadName+ ", redisName=" + redisName + "]";
    }

    @Override
    public Object call() throws Exception {
        String result = ":success";
        log.info(this.threadName+"=======[START]===" + this.toString());

        List<RepaymentOrder> list = redisCache.getCacheList(this.redisName);
        log.info("共有{}个代扣交易流水号需要执行", list.size());

        for (RepaymentOrder order : list) {
            log.info("代扣交易流水号{}开始执行跑批操作", order.getCustNo());

            try{
                boolean allReservedAccountOrder = iBRepaymentService.getAllReservedAccountOrder(order.getCustNo());
                if(allReservedAccountOrder){

                    RepaymentOrder repaymentOrder = new RepaymentOrder();
                    repaymentOrder.setRepaymentNo(order.getRepaymentNo());
                    repaymentOrder.setRepayStatus(1);
                    List<RepaymentOrder> repaymentOrders = iRepaymentOrderService.selectRepaymentOrderList(repaymentOrder);

                    if(repaymentOrders==null || repaymentOrders.size()==0){
                        //没找到   并且还款订单不为1（防止并发）   状态改为10
                        iBRepaymentService.closeByRepayemntNo(order.getRepaymentNo());
                    }
                }
            }catch (Exception e){
                log.error("代扣交易流水号{}执行跑批操作异常结束", order.getPayTransSerialNo());
                continue;
            }

            log.info("代扣交易流水号{}执行跑批操作正常结束", order.getPayTransSerialNo());
        }

        redisCache.deleteObject(this.redisName);

        log.info(this.threadName+"=======[END]===run result:" + result);
        return threadName + result;
    }
}
